package com.greenbook.utils;

import com.greenbook.properties.MinioProperties;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Data
@RequiredArgsConstructor
@Slf4j
@Component
public class MinioUtil {

    private final MinioProperties minioProperties;

    /**
     * 文件上传
     *
     * @param file
     * @param objectName
     * @return
     */
    public String upload(MultipartFile file, String objectName) {

        // 创建MinIOClient实例
        try(MinioClient minioClient = MinioClient.builder().endpoint(minioProperties.getEndpoint()).credentials(minioProperties.getAccessKeyId(), minioProperties.getAccessKeySecret()).build()) {
            // 创建PutObject请求
            minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
            );
            //获取图片预览链接
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET).bucket(minioProperties.getBucketName())
                            .object(objectName)
                            .build()
            );
            log.info("文件上传到:{}", url);
            return url;
        } catch (Exception e) {
            System.out.println("message:" + e.getMessage());
            System.out.println("cause:" + e.getCause());
        }
        return null;
    }
}
